import React,{useState,useRef,useEffect} from 'react'
import './index.scss'
import { ScaleViewContainer } from "react-scale-view";
import model from '../../../public/images/answer-model.svg'
import aa from '../../../public/images/chat-model.svg'
import day from '../../../public/images/day-model.svg'
import Video from '../../components/videoBarrage'
import SpeakText from '../../components/SpeakText'
import Avator from '../../components/avator/index.tsx'

import SlectOption from '../../components/selectOption/index.tsx'
//设置路由守卫
import Hoc_login from '../../components/Hoc/WithRouter'

import axios from 'axios';
import { message } from 'antd'; // 假设使用 antd 的 message 组件，需确保已安装 antd
import w2 from "../../assets/react.svg"
import aaa from "../../assets/react.svg"
// 数字人切换
import Model from '../../components/3Dmodel/model' 
import Tap from '../../components/3Dmodel/tap'
//Ai
import AI from '../../components/Aiso/index.tsx'

import { useNavigate } from'react-router-dom';

interface Props {
    
}


const Index = (props: Props) =>{ 
 const [aiInitialKeyword,setAiInitialKeyword]=useState('');
    //弹幕
    const videoRef = useRef<ReactPlayer>(null);
    //切换视频
 const [videos,setVideos]=useState([
   '/public/videos/rBsCHGRkJLuAAN0AE6kEocRcW-o399.mp4',
    '/public/videos/rBsCHGRjMUmAdnB7BuCLPLZ-E4U081.mp4',
    '/public/videos/rBsCHGRkJTiAC9PNAW5L7GYgaGc416.mp4',
    '/public/videos/rBsCHWRkJ26ADw9GAWlEkvvYZ8w683.mp4',
    '/public/videos/rBsCHWRkJPeARsU2Cvd4k4UZg-I610.mp4',
 ]);
 interface TokenResponse {
    access_token: string;
}

interface TextResponse {
    data: {
        result: string[];
    };
}

interface ChatResponse {
    data: {
        answer: string;
        conversation_id: string;
    };
}
   const getToken = async (): Promise<TokenResponse> => {
        try {
            const response = await axios.post('/getAIToken', {
                app_id: 'f94632e6-e650-41d3-889c-14171687dd09'
            }, {
                headers: {
                    'Content-Type': 'application/json',
                    'X-Appbuilder-Authorization': 'Bearer bce-v3/ALTAK-DJ7QNpQkM4TzQ2YHhjHml/f5756b73ca61bd5035850c35d6f3011bf7abf2a5'
                }
            });
            return response.data;
        } catch (error) {
            console.error('获取 token 失败', error);
            throw error;
        }
        
    };
 //存储当前视频的索引
 const [currentVideoIndex,setCurrentVideoIndex]=useState(0);
const [backgroundImage, setBackgroundImage] = useState('url(../../../public/images/indexLightBackground.png)');
const [backgroundSize, setBackgroundSize] = useState('cover');
//顶部图片
const [backgroundTopImage, setBackgroundTopImage] = useState('url(../../../public/images/ceil-day.png)');
//底部图片
const [backgroundBottomImage, setBackgroundBottomImage] = useState('url(../../../public/images/floor-day.png)');
//底部太阳月亮切换
const [sun, setSun] = useState('url(../../../public/images/day-model.svg)');
//ai聊天框显示隐藏切换
const [targetBoxVisible,setTargetBoxVisible]=useState<boolean>(false)
  const [img,setImg]=useState(true);
    const [flag, setFlag] = useState(false);
    const [isRecording, setIsRecording] = useState(false);
    const [transcript, setTranscript] = useState(''); // 存储识别
      const [listShow, setListShow] = useState(false);
const SwitchTheme = () => {
 setBackgroundImage(backgroundImage=='url(../../../public/images/indexLightBackground.png)'?'url(../../../public/images/bg-day.png)':'url(../../../public/images/indexLightBackground.png)')
 setBackgroundTopImage(backgroundTopImage=='url(../../../public/images/ceil-day.png)'?'url(../../../public/images/ceil.png)':'url(../../../public/images/ceil-day.png)');
 setBackgroundBottomImage(backgroundBottomImage=='url(../../../public/images/floor-day.png)'?'url(../../../public/images/floor.png)':'url(../../../public/images/floor-day.png)');
 setSun(sun=='url(../../../public/images/day-model.svg)'?'url(../../../public/images/night-model.svg)':'url(../../../public/images/day-model.svg)');
    console.log('切换主题')
    
}
  const chat = async (token: string, myText: string, conversation_id: string): Promise<ChatResponse> => {
        try {
            const response = await axios.post('/chat', {
                app_id: 'f94632e6-e650-41d3-889c-14171687dd09',
                query: myText,
                conversation_id,
                stream: false
            }, {
                headers: {
                    'Content-Type': 'application/json',
                    'X-Appbuilder-Authorization': `Bearer ${token}`
                }
            });
            return response.data;
        } catch (error) {
            console.error('调用聊天接口失败', error);
            throw error;
        }
    };
      const recorder = {
        start: () => console.log('recorder start'),
        stop: () => console.log('recorder stop'),
        getPCMBlob: () => new Blob([], { type: 'audio/pcm' })
    };
     const getText = async (token: string, base64data: string, size: number): Promise<TextResponse> => {
        try {
            const response = await axios.post('/转文字接口路径', {
                // 假设接口需要的参数
                token,
                base64data,
                size
            }, {
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            return response.data;
        } catch (error) {
            console.error('调用转文字接口失败', error);
            throw error;
        }
    };
      const entSpeak = () => {
        setSpeaking(false);
        message.info('讲话结束');
        recorder.stop();
        const babo = recorder.getPCMBlob();
        const reader = new FileReader();
        reader.readAsDataURL(babo);
        reader.onload = async (e) => {
            const base64 = e.target?.result as string;
            const base64data = base64.split(',')[1];
            const res = await getText(yytoken, base64data, babo.size);
            const { data: { result: [myText] } } = res;
            setList((list1) => [...list1, { text: myText, id: Math.random().toString().slice(1, 7), flag: 1 }]);

            const { data: { conversation_id } } = await getToken();
            const { data: chatData } = await chat(yytoken, myText, conversation_id);
            const { answer } = chatData;
            console.log(answer, 'answer');
            setList((l) => [...l, { text: answer, id: Math.random().toString().slice(1, 7), flag: 2 }]);

            const synth = window.speechSynthesis;
            const utterance = new SpeechSynthesisUtterance(answer);
            utterance.lang = 'zh-CN';
            utterance.rate = 1.0;
            synth.onvoiceschanged = () => {
                const voices = synth.getVoices();
                utterance.voice = voices[63];
                synth.speak(utterance);
            };
        };
    };
  
    const [speaking, setSpeaking] = useState(false);
    const [list, setList] = useState<any[]>([]);
    const [yytoken, setYyToken] = useState('');
        useEffect(() => {
        getToken().then((res) => {
            console.log(res,'res11111');
            setYyToken(res.access_token);
        }).catch((err) => {
            console.error(err, 'err');
        });
    }, []);
//自动切换视频
useEffect(()=>{
  const interval = setInterval(() => {
    setCurrentVideoIndex((prevIndex) => (prevIndex + 1) % videos.length);
  },10000);
  //清除定时器
  return () => clearInterval(interval);
});
 useEffect(() => {
        // 创建语音识别实例，注意不同浏览器可能需要添加前缀
        //@ts-expect-error
        const recognition = new (window.webkitSpeechRecognition || window.SpeechRecognition)();
        recognition.lang = 'zh-CN'; // 设置识别语言，可根据需要修改，如'zh-CN'表示中文

        // 当语音识别开始时执行的函数，打印“开始录音”
        recognition.onstart = () => {
            console.log('开始录音');
                  setSpeaking(false);
        message.info('讲话结束');
        recorder.stop();
        const babo = recorder.getPCMBlob();
        const reader = new FileReader();
        reader.readAsDataURL(babo);
        reader.onload = async (e) => {
            const base64 = e.target?.result as string;
            const base64data = base64.split(',')[1];
            const res = await getText(yytoken, base64data, babo.size);
            const { data: { result: [myText] } } = res;
            setList((list1) => [...list1, { text: myText, id: Math.random().toString().slice(1, 7), flag: 1 }]);

            const { data: { conversation_id } } = await getToken();
            const { data: chatData } = await chat(yytoken, myText, conversation_id);
            const { answer } = chatData;
            console.log(answer, 'answer');
            setList((l) => [...l, { text: answer, id: Math.random().toString().slice(1, 7), flag: 2 }]);

            const synth = window.speechSynthesis;
            const utterance = new SpeechSynthesisUtterance(answer);
            utterance.lang = 'zh-CN';
            utterance.rate = 1.0;
            synth.onvoiceschanged = () => {
                const voices = synth.getVoices();
                utterance.voice = voices[63];
                synth.speak(utterance);
            };
        };
        };

        // 当语音识别到结果时执行的函数
        recognition.onresult = (event: any) => {
            const transcript = event.results[0][0].transcript;
            setTranscript(transcript); // 存储识别出的文本
            console.log('识别出的文本:', transcript);
        };

        // 当语音识别出错时执行的函数，根据不同错误类型进行不同处理
        recognition.onerror = (error: any) => {
            console.log('语音识别出错:', error.error);
            if (error.error === 'not-allowed') {
                console.log('用户未授予麦克风权限');
            } else if (error.error === 'audio-capture') {
                console.log('未检测到音频输入');
            } else if (error.error === 'network') {
                console.log('网络错误');
            } else if (error.error === 'no-speech') {
                console.log('未检测到语音');
            } else if (error.error === 'service-not-allowed') {
                console.log('服务不允许');
            } else if (error.error === 'bad-grammar') {
                console.log('语法错误');
            } else if (error.error === 'language-not-supported') {
                console.log('不支持的语言');
            }
        };

        // 当语音识别结束时执行的函数，设置录音状态为 false 并打印“录音结束”
        recognition.onend = () => {
            setIsRecording(false);
            console.log('录音结束');
        };

        if (isRecording) {
            recognition.start();
        }
        return () => {
            recognition.stop();
        };
    }, [isRecording]);

    const startRecording = () => {
        setIsRecording(true);
    };

    const stopRecording = () => {
        setIsRecording(false);
    };
//切换图片
 const [isSpeaking,setIsSpeaking]=useState(true);
 //切换语音播放图片
    const RevImg = () => {
        setIsSpeaking(prevState=>!prevState);
        setImg(!img);
        setFlag(true);
        if (isRecording) {
            stopRecording();
        } else {
            startRecording();
        }

        setTargetBoxVisible(true);
    };

    const ConSImg = () => {
        setImg(!img);
        setFlag(false);
    };

// 切换到上一个视频
    const prevVideo = () => {
      console.log('切换到上一个视频')
        if (currentVideoIndex > 0) {
            setCurrentVideoIndex(currentVideoIndex - 1);
        } else {
            setCurrentVideoIndex(videos.length - 1);
        }
    };
    // 切换到下一个视频
    const nextVideo = () => {
        if (currentVideoIndex < videos.length - 1) {
            setCurrentVideoIndex(currentVideoIndex + 1);
        } else {
            setCurrentVideoIndex(0);
        }
    };

  //切换底部语音播放图片

 //切换动作
 const [selectedOption, setSelectedOption] = useState('option1');

    
    //跳转到3D展览馆
    const navigate = useNavigate();
    const enter3D = () => {
       navigate('/3D')
    }
    // 控制视频控制按钮的显示状态
    const [showControls, setShowControls] = useState(true);
    // 处理鼠标移入事件
    const handleMouseEnter = () => {
      console.log('鼠标移入')
      if(!showControls){
        setShowControls(true);
        
      }
      
    };


    // 处理鼠标移出事件
    const handleMouseLeave = () => {
        setShowControls(false);
        console.log('鼠标移出');

    };
   const handleSpeechToTextChange=(text:string)=>{
    setAiInitialKeyword(text);
    setTargetBoxVisible(false);
   }
    return (
        <ScaleViewContainer

        config={{

        width: 1920, // (必选)容器宽度；如 1920，

        height: 1080, // (必选)容器高度；如 1080，

        scaleType: "FULL_SCREEN",

        }}
       
>

        <div className='home-page'>
            <div className="top" style={{backgroundImage:backgroundTopImage,backgroundSize:'cover'}}>
                    <span>
                        <Avator/>
                    </span>
                {/* <img src="../../../public/images/ceil-day.png" alt="" /> */}
                    <span className='notice'><img src="../../../public/images/notice.gif" alt="" style={{width:"35px",height:'35px'}} /></span>
                 <span className='enter' onClick={enter3D}>进入3D展览馆</span>
                 <button onClick={SwitchTheme}  className='Btn-theme'>切换主题</button>
            </div>
            <div className="main">
             <div className="main1" style={{backgroundImage,backgroundSize:'cover'}}>
                <div className="left">
                  <SlectOption/>
                   {/* <Tap></Tap> */}
                  {/* <Model></Model> */}
                </div>
                 
                  <div className="dm">
                    <Video videoRef={videoRef} />
                       
                </div>
                {
                    targetBoxVisible && (
                        <div className="ai">
                    {/* <AI initialKeyword={aiInitialKeyword}></AI> */}
                    <SpeakText></SpeakText>
                 </div>
                    )
                }
                 
                <div className="right">
                  
                    <video src={videos[currentVideoIndex]} autoPlay muted controls ></video>
                 
                   
                </div>
              
             </div>
            </div>
            <div className="bottom" style={{backgroundImage:backgroundBottomImage,backgroundSize:'cover'}}>
              {/* 语音 */}
              <div className="voice" onClick={RevImg}>
                <img src={isSpeaking? "../../../public/images/speaking.jpeg":'../../../public/images/speeching.gif'}  alt="" />
                  <div>
            
                
            <p style={{color:'red',fontSize:'20px',}}>{transcript}</p> {/* 显示识别出的文本 */}
        </div>
              </div>
              <div className="right">
                  <span><img src={model} alt=""  /></span>
                   <span><img src={aa} alt="" /></span> 
                     <span><img src={day} alt="" onClick={SwitchTheme}/>
                     </span> 
                      
              </div>
            </div>
              <div className="video-controls" onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave}>
                <button onClick={prevVideo} className='btn1'>&lt;</button>
                <button onClick={nextVideo} className='btn2'>&gt;</button>
                        <div className="scoketList" style={{ display: listShow? 'block' : 'none' }}>
            <div className="speakX" onClick={() => setListShow(false)}>
                X
            </div>
            {list.map((item) => {
                return item.flag === 1? (
                    <div key={item.id} className="speak_left">
                        <img src={aaa} alt='' /><span>{item.text}</span>
                    </div>
                ) : (
                    <div key={item.id} className="speak_right">
                        <span>{item.text}</span><img src={w2} alt='' />
                    </div>
                );
            })}
        </div>
            </div>
        </div>
        </ScaleViewContainer>
    )
}


export default Hoc_login(Index)